package com.xiaoshuidi.cloud.module.rooms.controller.admin.roomhouse;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.xiaoshuidi.cloud.framework.common.pojo.CommonResult;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.security.core.util.SecurityFrameworkUtils;
import com.xiaoshuidi.cloud.module.rooms.api.roomhouse.vo.FreezeRepairReqVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.apartment.vo.ApartmentVO;
import com.xiaoshuidi.cloud.module.rooms.controller.admin.roomhouse.vo.*;
import com.xiaoshuidi.cloud.module.rooms.enums.ApiConstants;
import com.xiaoshuidi.cloud.module.rooms.framework.utils.CodeUtil;
import com.xiaoshuidi.cloud.module.rooms.service.RoomHouseService;
import com.xiaoshuidi.cloud.module.rooms.vo.RoomHouseRespVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Tag(name = "管理后台 - 房源管理")
@RestController
@RequiredArgsConstructor
@RequestMapping(ApiConstants.NAME + "/roomhouse")
public class RoomHouseController {

    private final RoomHouseService roomHouseService;
    private final CodeUtil codeUtil;
    private final StringRedisTemplate redisTemplate;


    @Operation(summary = "集中式新增房源")
    @PostMapping("/concentratedadd")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:concentrated-create')")
    public CommonResult<Boolean> concentratedAdd(@RequestBody @Valid ConcentratedAddVO concentratedAddVO) {
        Long tenantId = SecurityFrameworkUtils.getLoginUser().getTenantId();
        return roomHouseService.concentratedAdd(concentratedAddVO, tenantId);
    }

    @Operation(summary = "分散式新增房源")
    @PostMapping("/noconcentratedadd")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:no-concentrated-create')")
    public CommonResult<Boolean> noConcentratedAdd(@RequestBody @Valid NoConcentratedAddVO noConcentratedAddVO) {
        Long tenantId = SecurityFrameworkUtils.getLoginUser().getTenantId();
        return roomHouseService.noConcentratedAdd(noConcentratedAddVO, tenantId);
    }

    @Operation(summary = "编辑时获取房源信息")
    @Parameter(name = "roomHouseId", description = "房源(房间)id")
    @GetMapping("/getroomhouseinfo")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<RoomHouseInfoRespVO> getRoomHouseInfo(@RequestParam Long roomHouseId) {
        Long tenantId = SecurityFrameworkUtils.getLoginUser().getTenantId();
        return roomHouseService.getRoomHouseInfo(roomHouseId, tenantId);
    }

    @Operation(summary = "查看房源信息")
    @Parameter(name = "roomHouseId", description = "房源(房间)id")
    @GetMapping("/room-house-info")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<HouseInfoRespVO> roomHouseInfo(@RequestParam Long roomHouseId) {
        return roomHouseService.roomHouseInfo(roomHouseId);
    }


    @Operation(summary = "获取房源信息")
    @Parameter(name = "roomHouseId", description = "房源(房间)id")
    @GetMapping("/getroomhouseinfobyid")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<RoomHouseRespVo> getRoomHouseinfoById(@RequestParam("roomHouseId") Long roomHouseId) {
        return roomHouseService.getRoomHouseinfoById(roomHouseId);
    }

    @Operation(summary = "集中式编辑房源信息")
    @PutMapping("/concentratededit")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Boolean> concentratedEdit(@RequestBody @Valid ConcentratedRoomHouseEditReqVO editReqVO) {
        return roomHouseService.concentratedEdit(editReqVO);
    }

    @Operation(summary = "分散式编辑房源信息")
    @PutMapping("/noconcentratededit")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Boolean> noconcentratededit(@RequestBody @Valid NoConcentratedRoomHouseEditReqVO editReqVO) {
        return roomHouseService.noConcentratedEdit(editReqVO);
    }

    @Operation(summary = "切换为合租时获取子房源信息")
    @GetMapping("/get-sub-listings-when-switching-to-shared-apartments")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<List<SlaveRoomInfo>> getSubListingsWhenSwitchingToSharedApartments(Long roomHouseId) {
        return roomHouseService.getSubListingsWhenSwitchingToSharedApartments(roomHouseId);
    }

    @Operation(summary = "分散式房源出租形式变更")
    @PostMapping("/no-concentrated-edit-rental-method")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Boolean> noConcentratedEditRentalMethod(@RequestBody @Valid NoConcentratedRoomHouseEditReqVO editReqVO) {
        return roomHouseService.noConcentratedEditRentalMethod(editReqVO);
    }

    @Operation(summary = "房源删除")
    @Parameter(name = "roomHouseId", description = "房源(房间)id")
    @DeleteMapping("/delete")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:delete')")
    public CommonResult<Boolean> delete(@RequestParam("roomHouseId") Long roomHouseId) {
        return roomHouseService.delete(roomHouseId);
    }

    @Operation(summary = "房源报修")
    @Parameter(name = "roomHouseId", description = "房源(房间)id")
    @PostMapping("/repair")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Boolean> repair(@RequestBody FreezeRepairReqVO freezeRepairReqVO) {
        return roomHouseService.repair(freezeRepairReqVO.getRoomHouseId());
    }

    @Operation(summary = "房源报修 - 完成")
    @Parameter(name = "roomHouseId", description = "房源(房间)id")
    @PostMapping("/repairfinish")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Boolean> repairFinish(@RequestBody FreezeRepairReqVO freezeRepairReqVO) {
        Long tenantId = SecurityFrameworkUtils.getLoginUser().getTenantId();
        return roomHouseService.repairFinish(freezeRepairReqVO.getRoomHouseId());
    }

    @Operation(summary = "样板房切换")
    @Parameter(name = "roomHouseId", description = "房源(房间)id")
    @PostMapping("/screed")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Boolean> screed(@RequestBody FreezeRepairReqVO freezeRepairReqVO) {
        return roomHouseService.screed(freezeRepairReqVO.getRoomHouseId());
    }

    @Operation(summary = "房间冻结")
    @PostMapping("/roomfreeze")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Long> roomFreeze(@RequestBody FreezeRepairReqVO freezeRepairReqVO) {
        return roomHouseService.roomFreeze(freezeRepairReqVO.getRoomHouseId());
    }

    @Operation(summary = "房间解冻")
    @PostMapping("/roomunfreeze")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Long> roomUnFreeze(@RequestBody FreezeRepairReqVO freezeRepairReqVO) {
        return roomHouseService.roomUnFreeze(freezeRepairReqVO.getRoomHouseId());
    }

    @Operation(summary = "冻结部门下的所有房源")
    @Parameters({
            @Parameter(name = "deptId", description = "部门Id"),
    })
    @PostMapping("/room-freeze-by-deptId")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Boolean> roomFreezeByDeptId(@RequestParam("deptId") Long deptId) {
        return roomHouseService.roomFreezeByDeptId(deptId);
    }

    @Operation(summary = "解冻部门下的所有房源")
    @Parameters({
            @Parameter(name = "deptId", description = "部门Id"),
    })
    @PostMapping("/room-un-freeze-by-deptId")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Boolean> roomUnFreezeByDeptId(@RequestParam("deptId") Long deptId) {
        return roomHouseService.roomUnFreezeByDeptId(deptId);
    }

    @Operation(summary = "根据id列表获取房间信息")
    @Parameters({
            @Parameter(name = "ids", description = "id列表"),
    })
    @GetMapping("/getroomhousebyids")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<List<RoomHouseRespVo>> getRoomHouseByIds(@RequestParam("ids") List<Long> ids) {
        return roomHouseService.getRoomHouseByIds(ids);
    }

    @Operation(summary = "根据房源id获取对应门店信息")
    @Parameters({
            @Parameter(name = "roomHouseId", description = "房源id"),
    })
    @GetMapping("/get-apartment-info-by-room-house")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<ApartmentVO> getApartmentInfoByRoomHouse(@RequestParam("roomHouseId") Long roomHouseId) {
        return roomHouseService.getApartmentInfoByRoomHouse(roomHouseId);
    }

    /**
     * 分散式房源-导入
     *
     * @param req
     * @return
     */
    @Operation(summary = "分散式房源-导入")
    @PostMapping("/house-import")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:import')")
    public CommonResult<String> houseImport(@RequestBody HouseImportReq req) {
        Long tenantId = SecurityFrameworkUtils.getLoginUser().getTenantId();
        Long userId = SecurityFrameworkUtils.getLoginUser().getId();
//        Long tenantId = 2L;
//        Long userId = 2L;
        req.setTenantId(tenantId);
        req.setUserId(userId);
        String key ="room:house:"+ codeUtil.nextCode("IM");
        roomHouseService.houseImport(req, key);
        RoomHouseImportResult roomHouseImportResult = new RoomHouseImportResult(1, "导入中");
        redisTemplate.opsForValue().set(key, JsonUtils.toJsonString(roomHouseImportResult),1, TimeUnit.HOURS);
        return CommonResult.success(key);
    }

    /**
     * 查询分散式导入的状态
     *
     * @param key
     * @return
     */
    @Operation(summary = "查询分散式导入的状态")
    @GetMapping("/get-import-status/{code}")
    @Parameter(name = "key", description = "key")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<RoomHouseImportResult> getImportStatus(@PathVariable("code") String key) {
        String value = redisTemplate.opsForValue().get(key);
        RoomHouseImportResult result = JsonUtils.parseObject(value, RoomHouseImportResult.class);
        return CommonResult.success(result);
    }

    @Operation(summary = "所有小区/楼栋名称的树形结构")
    @Parameters({
            @Parameter(name = "isConcentrated", description = "是否集中式")
    })
    @GetMapping("/getroomhousetree")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<List<GetRoomHouseTreeRespVO>> getRoomHouseTree(@RequestParam("isConcentrated") Boolean isConcentrated) {
        return roomHouseService.getRoomHouseTree(isConcentrated);
    }

    @Operation(summary = "获取所有房源列表")
    @GetMapping("/all-room-house")
    @Parameters({
            @Parameter(name = "apartmentId", description = "门店地"),
            @Parameter(name = "isConcentrated", description = "是否集中式"),
            @Parameter(name = "houseState", description = "房态"),
            @Parameter(name = "isLock", description = "是否锁定"),
    })
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<List<AllRoomHouseRespVO>> allRoomHouse(@RequestParam("apartmentId") Long apartmentId, Boolean isConcentrated, String houseState, Boolean isLock) {
        Long tenantId = SecurityFrameworkUtils.getLoginUser().getTenantId();
        return roomHouseService.allRoomHouse(tenantId, apartmentId, isConcentrated, houseState, isLock, false);
    }

    @Operation(summary = "根据租客的手机号查询对应的房源信息")
    @Parameter(name = "phone", description = "租客手机号")
    @GetMapping("/get-room-house-by-tenant-phone")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<GetRoomHouseByTenantPhoneRespVO> getRoomHouseByTenantPhone(String phone){
        Long tenantId = SecurityFrameworkUtils.getLoginUser().getTenantId();
        return roomHouseService.getRoomHouseByTenantPhone(tenantId, phone);
    }

    @Operation(summary = "只获取所有主房源列表")
    @GetMapping("/primary-all-room-house")
    @Parameters({
            @Parameter(name = "apartmentId", description = "门店地"),
            @Parameter(name = "isConcentrated", description = "是否集中式"),
            @Parameter(name = "houseState", description = "房态"),
            @Parameter(name = "isLock", description = "是否锁定"),
    })
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<List<AllRoomHouseRespVO>> primaryAllRoomHouse(@RequestParam("apartmentId") Long apartmentId, Boolean isConcentrated, String houseState, Boolean isLock) {
        Long tenantId = SecurityFrameworkUtils.getLoginUser().getTenantId();;
        return roomHouseService.allRoomHouse(tenantId, apartmentId, isConcentrated, houseState, isLock, true);
    }


    @Operation(summary = "集中式-根据小区信息和楼栋回显房源信息")
    @Parameters({
            @Parameter(name = "province", description = "省"),
            @Parameter(name = "city", description = "市"),
            @Parameter(name = "district", description = "区"),
            @Parameter(name = "street", description = "街道"),
            @Parameter(name = "address", description = "详细地址"),
            @Parameter(name = "areaName", description = "小区名"),
            @Parameter(name = "buildingNo", description = "楼栋号")
    })
    @GetMapping("/room-house-info-by-area")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<ConcentratedAddVO> getRoomHouseInfoByAreaBuilding(@RequestParam("province") String province,
                                                                          @RequestParam("city") String city,
                                                                          @RequestParam("district") String district,
                                                                          @RequestParam("street") String street,
                                                                          @RequestParam("address") String address,
                                                                          @RequestParam("areaName") String areaName,
                                                                          @RequestParam("buildingNo") String buildingNo) {
        return roomHouseService.getRoomHouseInfoByAreaBuilding(province, city, district, street, address, areaName, buildingNo);
    }


    @Operation(summary = "分散式-根据小区信息和楼栋单元回显房源信息")
    @Parameters({
            @Parameter(name = "province", description = "省"),
            @Parameter(name = "city", description = "市"),
            @Parameter(name = "district", description = "区"),
            @Parameter(name = "street", description = "街道"),
            @Parameter(name = "address", description = "详细地址"),
            @Parameter(name = "areaName", description = "小区名"),
            @Parameter(name = "buildingNo", description = "楼栋号"),
            @Parameter(name = "unitNo", description = "单元号")
    })
    @GetMapping("/no-concentrate-room-house-info-by-area")
    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public CommonResult<NoConcentratedEchoRespVO> getNoConcentrateRoomHouseInfoByAreaBuilding(@RequestParam("province") String province,
                                                                                              @RequestParam("city") String city,
                                                                                              @RequestParam("district") String district,
                                                                                              @RequestParam("street") String street,
                                                                                              @RequestParam("address") String address,
                                                                                              @RequestParam("areaName") String areaName,
                                                                                              @RequestParam("buildingNo") String buildingNo,
                                                                                              @RequestParam("unitNo") String unitNo) {
        return roomHouseService.getNoConcentrateRoomHouseInfoByAreaBuilding(province, city, district, street, address, areaName, buildingNo, unitNo);
    }


    @Operation(summary = "导出分散式房源模板的接口")
    @GetMapping(value = "/download-house-template")
    @Parameters({
            @Parameter(name = "request", description = "请求"),
            @Parameter(name = "response", description = "响应"),
    })
    //@PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:query')")
    public void downloadHouseTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        ServletOutputStream out = response.getOutputStream();
//        response.setContentType("multipart/form-data");
//        response.setCharacterEncoding("UTF-8");
////        String fileName = "分散式房源导入模板.xlsx";
//        String fileName = "templates/a.xlsx";
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
//        InputStream inputStream = new ClassPathResource(fileName).getInputStream();
//        ExcelWriter writer = EasyExcel.write(out).withTemplate(inputStream)
//                        .excelType(ExcelTypeEnum.XLSX).build();
//        writer.finish();
//        out.flush();


        ClassPathResource resource = new ClassPathResource("/templates/a.xlsx");
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + "a.xlsx");
        try {
            ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate((resource.getInputStream())).build();
            excelWriter.finish();
        } catch (Exception e) {
            log.error("导入模板下载异常", e);
        }
    }

    @Operation(summary = "编辑脏房净房")
    @PutMapping("/isClean-roomHouse")
    @Parameters({
            @Parameter(name = "roomHouseId",description = "房间id"),
            @Parameter(name = "isClean",description = "净房还是脏房")
    })
//    @PreAuthorize("@ss.hasAnyPermissions('rooms:roomhouse:edit')")
    public CommonResult<Boolean> isCleanRoomHouseEdit(Long roomHouseId,Boolean isClean) {
        log.info("编辑房源脏房净房{} {}###########",roomHouseId,isClean);
        return roomHouseService.isCleanRoomHouseEdit(roomHouseId,isClean);
    }

    @Operation(summary = "编辑维修房")
    @PutMapping("/isRepair-roomHouse")
    @Parameters({
            @Parameter(name = "roomHouseId",description = "房间id"),
            @Parameter(name = "isRepair",description = "是否维修房")
    })
    public CommonResult<Boolean> isRepairRoomHouseEdit(Long roomHouseId,Boolean isRepair) {
        log.info("编辑房源维修房{} {}###########",roomHouseId,isRepair);
        return roomHouseService.isRepairRoomHouseEdit(roomHouseId,isRepair);
    }

}
